<?php defined('SYSPATH') or die();?>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
{php echo Common::js('html2canvas.js');}
{php echo Common::js('jquery.min.js');}
{php echo Common::js('jquery.layer.js');}
{Common::css_plugin('fenxiao_jieshao.css','fenxiao')}
{Common::js_plugin('jquery-qrcode.js','fenxiao')}
{if empty($product_code_pic) && $fenxiao_pic_templet=='1'}
{Common::css_plugin('fenxiao_jieshao_tpl1.css','fenxiao')}
{/if}
<div class="share-page-container" id="sharePageContainer" style="display: none;">

    <div class="share-page-content">
        {if !empty($fenxiao_profit) && $fenxiao_profit!=0}
        <div class="share-prospect-price">本次分销预估收益<span class="prospect-item">{Currency_Tool::symbol()}{$fenxiao_profit}</span></div>
        {/if}
        <div class="share-type-wrap">
            {if in_array('weixin',$fenxiao_ways)}
            <div class="wechat-box">
                <div class="hd">微信分销<br><img src="{$GLOBALS['cfg_public_url']}images/share-icon_03.png"></div>
                <div class="bd">请在微信浏览器内点击微信右上角<img src="{$GLOBALS['cfg_public_url']}images/wechat-operate-icon1.png">按钮，通过【发送给朋友】、【分享到朋友圈】进行分享</div>
            </div>
            {/if}
            <ul class="other-box clearfix">
                {if in_array('pic',$fenxiao_ways)}
                <li>
                    <a class="item" href="javascript:;" id="sharePicFx">
                        <i class="icon tp-icon"></i>
                        <span class="name">图片分销</span>
                    </a>
                </li>
                {/if}
                {if in_array('weibo',$fenxiao_ways)}
                <li>
                    <a class="item" href="http://v.t.sina.com.cn/share/share.php?url={urlencode($url)}&title={$weibo_content}">
                        <i class="icon xl-icon"></i>
                        <span class="name">新浪微博</span>
                    </a>
                </li>
                {/if}
                {if in_array('codescan',$fenxiao_ways)}
                <li>
                    <a class="item" href="javascript:;" id="shareFaceToFace">
                        <i class="icon sm-icon"></i>
                        <span class="name">当面扫码</span>
                    </a>
                </li>
                {/if}
                {if in_array('link',$fenxiao_ways)}
                <li>
                    <a class="item" href="javascript:;" id="shareCopyLink">
                        <i class="icon lj-icon"></i>
                        <span class="name">复制链接</span>
                    </a>
                </li>
                {/if}
            </ul>
        </div>
    </div>
    <div class="share-page-code" id="sharePageCode" style="display: none;">
        <div class="code-img"><img src="//{$GLOBALS['main_host']}/res/vendor/qrcode/make.php?param={$url}"></div>
    </div>
    <div class="share-page-img" id="sharePageImg" style="display: none;">
        <img style="width: 100%;margin-top: 1.2rem" src="{$imgpath}"/>
    </div>
    <div class="share-page-copy" id="sharePageCopy" style="display: none;">
        <div class="copy-box">
            <div class="copy-tit">长按文字 复制链接</div>
            <textarea class="copy-area" name="">{$copylink_content}</textarea>
        </div>
    </div>
    <a class="close-page-bar" id="closePageBar" href="javascript:;"><i class="close-icon"></i></a>

</div>

<script>

    var code_pic = "{$code_pic}";

    var Canvas2Image = function () {

        // check if support sth.
        var $support = function () {
            var canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d');

            return {
                canvas: !!ctx,
                imageData: !!ctx.getImageData,
                dataURL: !!canvas.toDataURL,
                btoa: !!window.btoa
            };
        }();

        var downloadMime = 'image/octet-stream';

        function scaleCanvas (canvas, width, height) {
            var w = canvas.width,
                h = canvas.height;
            if (width == undefined) {
                width = w;
            }
            if (height == undefined) {
                height = h;
            }

            var retCanvas = document.createElement('canvas');
            var retCtx = retCanvas.getContext('2d');
            retCanvas.width = width;
            retCanvas.height = height;
            retCtx.drawImage(canvas, 0, 0, w, h, 0, 0, width, height);
            return retCanvas;
        }

        function getDataURL (canvas, type, width, height) {
            canvas = scaleCanvas(canvas, width, height);
            return canvas.toDataURL(type);
        }

        function saveFile (strData) {
            document.location.href = strData;
        }

        function genImage(strData) {
            var img = document.createElement('img');
            img.src = strData;
            return img;
        }
        function fixType (type) {
            type = type.toLowerCase().replace(/jpg/i, 'jpeg');
            var r = type.match(/png|jpeg|bmp|gif/)[0];
            return 'image/' + r;
        }
        function encodeData (data) {
            if (!window.btoa) { throw 'btoa undefined' }
            var str = '';
            if (typeof data == 'string') {
                str = data;
            } else {
                for (var i = 0; i < data.length; i ++) {
                    str += String.fromCharCode(data[i]);
                }
            }

            return btoa(str);
        }
        function getImageData (canvas) {
            var w = canvas.width,
                h = canvas.height;
            return canvas.getContext('2d').getImageData(0, 0, w, h);
        }
        function makeURI (strData, type) {
            return 'data:' + type + ';base64,' + strData;
        }


        /**
         * create bitmap image
         * 按照规则生成图片响应头和响应体
         */
        var genBitmapImage = function (oData) {

            //
            // BITMAPFILEHEADER: http://msdn.microsoft.com/en-us/library/windows/desktop/dd183374(v=vs.85).aspx
            // BITMAPINFOHEADER: http://msdn.microsoft.com/en-us/library/dd183376.aspx
            //

            var biWidth  = oData.width;
            var biHeight	= oData.height;
            var biSizeImage = biWidth * biHeight * 3;
            var bfSize  = biSizeImage + 54; // total header size = 54 bytes

            //
            //  typedef struct tagBITMAPFILEHEADER {
            //  	WORD bfType;
            //  	DWORD bfSize;
            //  	WORD bfReserved1;
            //  	WORD bfReserved2;
            //  	DWORD bfOffBits;
            //  } BITMAPFILEHEADER;
            //
            var BITMAPFILEHEADER = [
                // WORD bfType -- The file type signature; must be "BM"
                0x42, 0x4D,
                // DWORD bfSize -- The size, in bytes, of the bitmap file
                bfSize & 0xff, bfSize >> 8 & 0xff, bfSize >> 16 & 0xff, bfSize >> 24 & 0xff,
                // WORD bfReserved1 -- Reserved; must be zero
                0, 0,
                // WORD bfReserved2 -- Reserved; must be zero
                0, 0,
                // DWORD bfOffBits -- The offset, in bytes, from the beginning of the BITMAPFILEHEADER structure to the bitmap bits.
                54, 0, 0, 0
            ];

            //
            //  typedef struct tagBITMAPINFOHEADER {
            //  	DWORD biSize;
            //  	LONG  biWidth;
            //  	LONG  biHeight;
            //  	WORD  biPlanes;
            //  	WORD  biBitCount;
            //  	DWORD biCompression;
            //  	DWORD biSizeImage;
            //  	LONG  biXPelsPerMeter;
            //  	LONG  biYPelsPerMeter;
            //  	DWORD biClrUsed;
            //  	DWORD biClrImportant;
            //  } BITMAPINFOHEADER, *PBITMAPINFOHEADER;
            //
            var BITMAPINFOHEADER = [
                // DWORD biSize -- The number of bytes required by the structure
                40, 0, 0, 0,
                // LONG biWidth -- The width of the bitmap, in pixels
                biWidth & 0xff, biWidth >> 8 & 0xff, biWidth >> 16 & 0xff, biWidth >> 24 & 0xff,
                // LONG biHeight -- The height of the bitmap, in pixels
                biHeight & 0xff, biHeight >> 8  & 0xff, biHeight >> 16 & 0xff, biHeight >> 24 & 0xff,
                // WORD biPlanes -- The number of planes for the target device. This value must be set to 1
                1, 0,
                // WORD biBitCount -- The number of bits-per-pixel, 24 bits-per-pixel -- the bitmap
                // has a maximum of 2^24 colors (16777216, Truecolor)
                24, 0,
                // DWORD biCompression -- The type of compression, BI_RGB (code 0) -- uncompressed
                0, 0, 0, 0,
                // DWORD biSizeImage -- The size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps
                biSizeImage & 0xff, biSizeImage >> 8 & 0xff, biSizeImage >> 16 & 0xff, biSizeImage >> 24 & 0xff,
                // LONG biXPelsPerMeter, unused
                0,0,0,0,
                // LONG biYPelsPerMeter, unused
                0,0,0,0,
                // DWORD biClrUsed, the number of color indexes of palette, unused
                0,0,0,0,
                // DWORD biClrImportant, unused
                0,0,0,0
            ];

            var iPadding = (4 - ((biWidth * 3) % 4)) % 4;

            var aImgData = oData.data;

            var strPixelData = '';
            var biWidth4 = biWidth<<2;
            var y = biHeight;
            var fromCharCode = String.fromCharCode;

            do {
                var iOffsetY = biWidth4*(y-1);
                var strPixelRow = '';
                for (var x = 0; x < biWidth; x++) {
                    var iOffsetX = x<<2;
                    strPixelRow += fromCharCode(aImgData[iOffsetY+iOffsetX+2]) +
                    fromCharCode(aImgData[iOffsetY+iOffsetX+1]) +
                    fromCharCode(aImgData[iOffsetY+iOffsetX]);
                }

                for (var c = 0; c < iPadding; c++) {
                    strPixelRow += String.fromCharCode(0);
                }

                strPixelData += strPixelRow;
            } while (--y);

            var strEncoded = encodeData(BITMAPFILEHEADER.concat(BITMAPINFOHEADER)) + encodeData(strPixelData);

            return strEncoded;
        };

        /**
         * saveAsImage
         * @param canvasElement
         * @param {String} image type
         * @param {Number} [optional] png width
         * @param {Number} [optional] png height
         */
        var saveAsImage = function (canvas, width, height, type) {
            if ($support.canvas && $support.dataURL) {
                if (typeof canvas == "string") { canvas = document.getElementById(canvas); }
                if (type == undefined) { type = 'png'; }
                type = fixType(type);
                if (/bmp/.test(type)) {
                    var data = getImageData(scaleCanvas(canvas, width, height));
                    var strData = genBitmapImage(data);
                    saveFile(makeURI(strData, downloadMime));
                } else {
                    var strData = getDataURL(canvas, type, width, height);
                    saveFile(strData.replace(type, downloadMime));
                }
            }
        };

        var convertToImage = function (canvas, width, height, type) {
            if ($support.canvas && $support.dataURL) {
                if (typeof canvas == "string") { canvas = document.getElementById(canvas); }
                if (type == undefined) { type = 'png'; }
                type = fixType(type);

                if (/bmp/.test(type)) {
                    var data = getImageData(scaleCanvas(canvas, width, height));
                    var strData = genBitmapImage(data);
                    return genImage(makeURI(strData, 'image/bmp'));
                } else {
                    var strData = getDataURL(canvas, type, width, height);
                    return genImage(strData);
                }
            }
        };



        return {
            saveAsImage: saveAsImage,
            saveAsPNG: function (canvas, width, height) {
                return saveAsImage(canvas, width, height, 'png');
            },
            saveAsJPEG: function (canvas, width, height) {
                return saveAsImage(canvas, width, height, 'jpeg');
            },
            saveAsGIF: function (canvas, width, height) {
                return saveAsImage(canvas, width, height, 'gif');
            },
            saveAsBMP: function (canvas, width, height) {
                return saveAsImage(canvas, width, height, 'bmp');
            },

            convertToImage: convertToImage,
            convertToPNG: function (canvas, width, height) {
                return convertToImage(canvas, width, height, 'png');
            },
            convertToJPEG: function (canvas, width, height) {
                return convertToImage(canvas, width, height, 'jpeg');
            },
            convertToGIF: function (canvas, width, height) {
                return convertToImage(canvas, width, height, 'gif');
            },
            convertToBMP: function (canvas, width, height) {
                return convertToImage(canvas, width, height, 'bmp');
            }
        };

    }();
    (function() {

        $("#share_btn").on("click", function () {
            $("html,body").css({
                height: "100%",
                overflow: "hidden"
            })
            $("#sharePageContainer").show();

        });


        $("#closePageBar").on("click", function () {
            $("#sharePageCode").hide();
            $("#sharePageImg").hide();
            $("#sharePageContainer").hide();
            $("#sharePageCopy").hide();
        });

        $("#shareFaceToFace").on("click", function () {
            $("#sharePageCode").show()
        });

        $("#sharePicFx").on("click", function () {
            $("#sharePageImg").show();
        });

        $("#shareCopyLink").on("click",function(){
            $("#sharePageCopy").show()
        })


    })();

    //微信相关
    (function(){

        weixin_data={};
        weixin_link="{$url}";
        weixin_title="{St_String::filter_js_str($weixin_title)}";
        weixin_litpic= "{$GLOBALS['cfg_basehost']}{Common::get_sys_para('cfg_m_logo',0)}";
        product_litpic = "{Common::img($product_litpic)}";
        weixin_sellpoint = "{St_String::filter_js_str($product_sellpoint)}";
        weixin_litpic = product_litpic?product_litpic:weixin_litpic;
        weixin_content = "";
        //微信分销
        $.ajax({
            type: "POST",
            url: SITEURL+'fenxiao/jieshao/ajax_get_weixininfo',
            data: {url:window.location.href},
            dataType: "json",
            success: function (result) {
                if(result.status)
                {
                    weixin_data = result.data;
                    weixin_share();
                }
            }
        });
        function weixin_share()
        {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: weixin_data['appid'], // 必填，公众号的唯一标识
                timestamp: weixin_data['timestamp'], // 必填，生成签名的时间戳
                nonceStr:weixin_data['noncestr'] , // 必填，生成签名的随机串
                signature: weixin_data['signature'],// 必填，签名，见附录1
                jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(function(){
                var content=$("#share_content").val();
                wx.onMenuShareTimeline({
                    title: weixin_title, // 分享标题
                    link: weixin_link, // 分享链接
                    imgUrl:weixin_litpic, // 分享图标
                    success: function () {

                    },
                    cancel: function () {

                    },
                    trigger:function(){
                        // this.title="我要分享";

                    }
                });
                wx.onMenuShareAppMessage({
                    title: weixin_title, // 分享标题
                    desc: weixin_sellpoint, // 分享描述
                    link: weixin_link, // 分享链接
                    imgUrl: weixin_litpic, // 分享图标
                    type: '', // 分享类型,music、video或link，不填默认为link
                    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                    success: function () {
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: function () {
                        // 用户取消分享后执行的回调函数
                    },
                    trigger:function(){
                        //this.desc=$("#share_edit_con").val();

                    }
                });
            })
            wx.error(function(res){

            });
        }
    })();
</script>